//
//  EmoticonViewController.swift
//  表情键盘
//
//  Created by 叶子韬韬 on 2017/5/10.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import UIKit
internal let EmotiocellIdentifier = "EmotiocellIdentifier"
class EmoticonViewController: UIViewController {
    
    // MARK:- #注释>定义闭包
    var emotiocnCallBack:(_ emoticon:Emoticon)->()
    
    
    // MARK:- #注释>自定义构造函数
    init(emotiocnCallBack:@escaping (_ emoticon:Emoticon)->()) {
        self.emotiocnCallBack = emotiocnCallBack
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    internal lazy var collectionView:UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmotioCollectionViewLayout())
    internal lazy var toolBar:UIToolbar = UIToolbar();
    internal lazy var manger:EmoticonManger = EmoticonManger()
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }



}
// MARK:- #注释>设置UI界面
extension EmoticonViewController{
    internal func setupUI(){
        
        
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        collectionView.backgroundColor = UIColor.white
     
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        //设置frame VFL
        let views = ["toolBar":toolBar,"collectionView":collectionView] as [String : Any]
        
        var cons =  NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-[toolBar]-0-|", options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        
        view.addConstraints(cons)
        
        //为collectionView 添加数据
        prepareForCollectionView()
        
        //准备toolbar
        prepareForToolBar()
    }
    
    internal func prepareForCollectionView(){
        
        //注册cell
        collectionView.register(EmoticonCell.self, forCellWithReuseIdentifier: EmotiocellIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        //设置布局

        
        
    }
    internal func prepareForToolBar(){
        
        let titles = ["最近","默认","emoji","浪小花"]
        
        //创建toolbar
        var indexx = 0
        var items = [UIBarButtonItem]()
        for title in titles {
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(self.itemCiick(item:)))
            item.tag = indexx
            indexx += 1
            items.append(item)
            //增弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        //设置toolbar的items数组
        toolBar.items = items
        //设置颜色
        toolBar.tintColor = UIColor.orange
    }
    
    internal func itemCiick(item:UIBarButtonItem){
        print(item.tag)
        let tag = item.tag
        
        let indexPath = IndexPath(item: 0, section: tag)
        
        //滚动到对应位置
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        
        
        
    }
    
    
}
extension EmoticonViewController : UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manger.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let packge = manger.packages[section]
        
        
        return packge.emoticons.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmotiocellIdentifier, for: indexPath) as! EmoticonCell
        
        let packge = manger.packages[indexPath.section]
        let emoticon = packge.emoticons[indexPath.item]
        cell.emoticon = emoticon
        
        
        return cell
    
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //先取出点击的表情
        let packge = manger.packages[indexPath.section]
        let emticon = packge.emoticons[indexPath.item]
        
        
        //将点击的表情插入到最近分组中
        insertRecentlyEmoticon(emticon: emticon)
        //将表情回调给闭包
        emotiocnCallBack(emticon)
        
    }
    
    internal func insertRecentlyEmoticon(emticon:Emoticon){
        
        
        // 1.如果是空白表情或者删除按钮,不需要插入
        if emticon.isRemove || emticon.isEmpty {
            return
        }
        
        // 2.删除一个表情
        if manger.packages.first!.emoticons.contains(emticon) { // 原来有该表情
            let index = (manger.packages.first?.emoticons.index(of: emticon))!
            manger.packages.first?.emoticons.remove(at: index)
        } else { // 原来没有这个表情
            manger.packages.first?.emoticons.remove(at: 19)
        }
        
        // 3.将emoticon插入最近分组中
        manger.packages.first?.emoticons.insert(emticon, at: 0)
        
    }
    
}

class EmotioCollectionViewLayout: UICollectionViewFlowLayout {
    
    override func prepare() {
        super.prepare()
        
        //计算item的宽度和高度
        let itemWH = UIScreen.main.bounds.width/7
        
        //设置layout的属性
        itemSize = CGSize.init(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        //设置分页
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        let insertMargin = ((collectionView?.bounds.height)! - 3*itemWH)/2
        collectionView?.contentInset = UIEdgeInsetsMake(insertMargin, 0, insertMargin, 0)
        
        
    }
    
}

